<template>
    <div class="turntable" id="turntable" ref="turntable">
        <div class="rotate" ref="rotate" id="rotate" @transitionend="end">
            <canvas :width="radius * 2" :height="radius * 2" ref="canvas" v-show="radius">抱歉！浏览器不支持。</canvas>
            <ul class="list">
                <li class="item" v-for="(item, index) in prizes" :style="textTransform(index)" :key="index">
                    <div class="item-con">
                        <div class="ingo">
                            {{ item.name.length > maxTextLength ? item.name.substr(0, maxTextLength).concat('..') : item.name }}
                            <span v-if="item.num > 0">
                                <span style="font-size:8px">x</span> {{ item.num.length > 2 ? item.num.substr(0, 2).concat('..') : item.num }}
                            </span>
                        </div>
                        <img :src="item.pic" alt="">
                    </div>
                </li>
            </ul>
        </div>

        <img class="pointer" :src="pointer" @click.stop="start" ref="pointer" />
    </div>
</template>

<script>
// 不同浏览器内核
let vendors = {
    '': '',
    Webkit: 'webkit',
    Moz: '',
    O: 'o',
    ms: 'ms'
};

export default {
    mixins: [],
    name: 'turntable',
    data() {
        return {
            //当前索引
            currentIndex: 0,
            //当前旋转角度
            currentDeg: 0,
            //上次中奖索引
            lastIndex: 0,
            //正在转
            isRun: false
        };
    },
    props: {
        //半径
        radius: {
            type: Number,
            default: 0
        },
        //奖品池
        prizes: {
            type: Array,
            isRequired: true,
            default: () => {
                return [];
            }
        },
        //颜色池
        colors: {
            type: Array,
            default: () => {
                return ['#FFF0AC', '#F8D0AC'];
            }
        },
        //指针图片
        pointer: {
            type: String,
            isRequired: true
        },
        //指针纵向偏移
        offset: {
            type: Number,
            default: 0
        },
        //文字最大长度
        maxTextLength: {
            type: Number,
            default: 5
        }
    },
    computed: {
        //奖品池数量
        size() {
            return this.prizes.length;
        },
        //几分之一，每个分区的turn数
        itemNum() {
            return 1 / this.size;
        },
        //每个分区的角度
        itemDeg() {
            return 360 / this.size;
        }
    },
    created() {
        this.testBrower();
    },
    mounted() {
        this.ctx = this.$refs.canvas.getContext('2d');
        this.imgOffset();
    },
    methods: {
        start() {
            if (this.isRun) {
                return;
            }
            this.$emit('start');
        },
        end() {
            this.isRun = false;
            let that = this
            var element = document.getElementById("rotate");
            element.addEventListener("transitionend", that.$emit('end'), false);
        },
        //绘制转盘
        draw() {
            if (this.size === 0 || this.radius === 0) return;
            if (!this.$refs.canvas.getContext) {
                alert('抱歉！浏览器不支持。');
                return;
            }

            //修改容器大小
            this.$refs.turntable.style.width = `${this.radius * 2}px`;
            this.$refs.turntable.style.height = `${this.radius * 2}px`;

            // 获取绘图上下文
            let ctx = this.ctx;
            let rotateDeg = 360 / this.size / 2 + 90; // 扇形回转角度
            for (var i = 0; i < this.size; i++) {
                // 保存当前状态
                ctx.save();
                // 开始一条新路径
                ctx.beginPath();
                // 位移到圆心，下面需要围绕圆心旋转
                ctx.translate(this.radius, this.radius);
                // 从(0, 0)坐标开始定义一条新的子路径
                ctx.moveTo(0, 0);
                // 旋转弧度,需将角度转换为弧度,使用 degrees * Math.PI/180 公式进行计算。
                ctx.rotate((((360 / this.size) * i - rotateDeg) * Math.PI) / 180);
                // 绘制圆弧
                ctx.arc(0, 0, this.radius, 0, (2 * Math.PI) / this.size, false);

                // 颜色间隔
                ctx.fillStyle = this.colors[i % this.colors.length];

                // 填充扇形
                ctx.fill();
                // 绘制边框
                // ctx.lineWidth = 0.5;
                // ctx.strokeStyle = '#e4370e';
                // ctx.stroke();

                // 恢复前一个状态
                ctx.restore();
            }
        },
        // 旋转多少角度
        runRotate(deg) {
            this.isRun = true;
            this.currentDeg += deg;
            this.$refs.rotate.style[this.cssSupport.transform] = 'rotate(' + this.currentDeg + 'deg)';
        },
        // 旋转至
        rotateTo(index) {
            let lastIndex = this.currentIndex;
            this.currentIndex = index;
            //前后两次的索引差
            let diff = this.currentIndex >= lastIndex ? this.currentIndex - lastIndex : this.size + this.currentIndex - lastIndex;
            let deg = diff * this.itemDeg + 2880;
            this.runRotate(deg);
        },
        testBrower() {
            const testEle = document.createElement('p');
            Object.keys(vendors).some((vendor) => {
                if (testEle.style[vendor + (vendor ? 'T' : 't') + 'ransitionProperty'] !== undefined) {
                    this.cssPrefix = vendor ? '-' + vendor.toLowerCase() + '-' : '';
                    this.eventPrefix = vendors[vendor];
                    return true;
                }
            });

            //css前缀
            this.cssSupport = {
                cssPrefix: this.cssPrefix,
                transform: this.normalizeCss('Transform'),
                transitionEnd: this.normalizeEvent('TransitionEnd')
            };
        },
        //兼容CSS前缀
        normalizeCss(name) {
            name = name.toLowerCase();
            return this.cssPrefix ? this.cssPrefix + name : name;
        },
        // 兼容事件前缀
        normalizeEvent(name) {
            return this.eventPrefix ? this.eventPrefix + name : name.toLowerCase();
        },
        //文字旋转样式
        textTransform(i) {
            //逆时针顺序 数值为负
            return `${this.cssSupport.transform}: rotate(-${i * this.itemNum}turn);`;
        },
        //指针图片纵向偏移
        imgOffset() {
            let trans = this.$refs.pointer.style.transform;
            this.$refs.pointer.style.transform = 'translate(-50%,-50%) translateY(' + this.offset + 'px)';
        }
    },
    watch: {
        // radius(val) {
        //     if (val > 0) {
        //         this.$nextTick(() => {
        //             this.draw();
        //         });
        //     }
        // },
        prizes(val) {
            if (val.length > 0 && this.radius > 0) {
                this.$nextTick(() => {
                    this.draw();
                });
            }
        },
    },
    components: {}
};
</script>

<style lang="stylus" scoped>
@import '~assets/main.styl';

* {
    box-sizing: border-box;
}

li {
    margin: 0;
    padding: 0;
    list-style: none;
}

.turntable {
    position: relative;
    /* width: vw(300);
    height: vw(300); */
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    border-radius: 50%;

    .rotate {
        position: absolute;
        left: 0;
        top: 0;
        z-index: 1;
        width: inherit;
        height: inherit;
        border-radius: inherit;
        -webkit-transition: all 6s ease;
        transition: all 6s ease;

        canvas {
            width: inherit;
            height: inherit;
            border-radius: 50%;
        }

        .list {
            position: absolute;
            left: 0;
            top: 0;
            width: inherit;
            height: inherit;
            z-index: 2;

            .item {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
                height: 100%;
                padding: vw(15);
                color: #e4370e;
                // font-weight: bold;
                text-shadow: 0 1px 1px rgba(255, 255, 255, 0.6);

                .item-con {
                    flex-y();
                }

                .ingo {
                    margin-bottom: vw(18);
                    font-size: vw(12);

                    span {
                        font-size: vw(10);
                    }
                }

                img {
                    width: vw(30);
                    height: vw(30);
                    margin-bottom: vw(30);
                }
            }
        }
    }

    .pointer {
        position: absolute;
        left: 50%;
        top: 50%;
        z-index: 3;
        width: vw(80);
        transform: translate(-50%, -50%);
    }
}
</style>
